<?php
class FriendModel extends Zend_Db_Table_Abstract {
	
	protected $_name = 'friend';
	protected $_id = 'id';
	
	public function listfriend($user_id){
		$db = Zend_Registry::get('connectDB');
		$select = $db->select()
					->from(array('f'=>'friend'),array('user_id'=>'f.user_id',
														'friend_id'=>'f.friend_id'))
					->join(array('u'=>'user'),'u.id = f.friend_id',array('username'=>'u.username',
																		'fullname'=>'u.fullname',
																		'avatar'=>'u.avatar'))
					->where('f.user_id ='.$user_id);
		$list = $db->fetchAll($select);
		return $list;
	}
	
	public function isfriend($user_id,$friend_id){
		$model = new FriendModel();
		$is = $model->fetchRow($model->select()->where('user_id = '.$user_id)->where('friend_id = '.$friend_id));
		if ($is||($user_id==$friend_id)) return 1;
		else return 0;
	}
	
	public function addfriend($user_id,$friend_id){
		$model = new FriendModel();
		$data = array('user_id'=>$user_id,'friend_id'=>$friend_id);
		$model->insert($data);
		$data = array('user_id'=>$friend_id,'friend_id'=>$user_id);
		$model->insert($data);
	}
	
	public function mutualfriend($user_id,$friend_id){
		$model = new FriendModel();
		$count = 0;
		$friend_user = $model->fetchAll($model->select()->where('user_id = '.$user_id));
		foreach ($friend_user as $friend){
			$mutual = $model->fetchRow($model->select()->where('user_id = '.$friend_id)->where('friend_id = '.$friend['friend_id']));
			if ($mutual) $count++;
		}
		return $count;
	}
}